﻿using Microsoft.EntityFrameworkCore;
using StuManager.model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StuManager
{
    public class SchoolContext : DbContext
    {
        public DbSet<School> Schools { get; set; }
        public DbSet<Class> Classes { get; set; }
        public DbSet<Student> Students { get; set; }
        public DbSet<Log> Logs { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // 使用SQLite数据库
            optionsBuilder.UseSqlite("Data Source=students.db");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // 配置表的关系
            modelBuilder.Entity<School>()
                .HasMany(s => s.Classes)
                .WithOne(c => c.School)
                .HasForeignKey(c => c.SchoolId);

            modelBuilder.Entity<Class>()
                .HasMany(c => c.Students)
                .WithOne(s => s.Class)
                .HasForeignKey(s => s.ClassId);
        }

        // 记录操作日志
        public void LogOperation(string operation)
        {
            Logs.Add(new Log { Operation = operation });
            SaveChanges();
        }
    }
}
